// pages/index_more/index_more.js
const app = getApp();
const baseUrl = app.getApiBaseUrl();

Page({
  data: {
    kind: '', // 从查询参数获取
    pageTitle: '',
    categoryLabel: '',
    expertPaths: [], // 学习路径列表
    isLoading: true,
    isLoggedIn: false,
    showHintPopup: false,
    hintMessage: '',
    page: 1, // 分页页码
    limit: 100, // 每页限制100条
    hasMore: false, // 是否有更多路径
  },

  onLoad(options) {
    const kind = options.kind || '';
    this.setData({ kind });
    this.setPageTitleAndLabel(kind);
    this.attemptLogin();
    // 确保分享菜单显示
    wx.showShareMenu({
      menus: ['shareAppMessage', 'shareTimeline'],
    });
  },

  // 设置页面标题和分类标签
  setPageTitleAndLabel(kind) {
    const kindMap = {
      pujiao: { title: '基础教育学习路径', label: '基础教育', dbKind: '普教' },
      gaojiao: { title: '高等教育学习路径', label: '高等教育', dbKind: '高教' },
      zhijiao: { title: '职业教育学习路径', label: '职业教育', dbKind: '职教' },
      congyezige: { title: '从业资格学习路径', label: '从业资格', dbKind: '从业资格' },
      zhongshen: { title: '终身学习路径', label: '终身学习', dbKind: '终身学习' },
    };
    const config = kindMap[kind] || { title: '学习路径', label: '学习', dbKind: '' };
    this.setData({
      pageTitle: config.title,
      categoryLabel: config.label,
    });
    wx.setNavigationBarTitle({ title: config.title });
  },

  // 尝试登录
  attemptLogin() {
    const app = getApp();
    this.setData({ isLoading: true });
    if (app.globalData.isLoggingIn) {
      app.globalData.loginPromise
        .then((res) => {
          this.handleLoginSuccess(res);
          this.loadExpertPaths();
          this.setData({ isLoading: false });
        })
        .catch((err) => {
          this.handleLoginFailure(err);
          this.setData({ isLoading: false });
        });
    } else {
      app.ensureValidToken()
        .then((res) => {
          this.handleLoginSuccess(res);
          this.loadExpertPaths();
          this.setData({ isLoading: false });
        })
        .catch((err) => {
          this.handleLoginFailure(err);
          this.setData({ isLoading: false });
        });
    }
  },

  // 处理登录成功
  handleLoginSuccess(res) {
    const unionID = res.unionID || '';
    this.setData({
      isLoggedIn: !!unionID,
    });
  },

  // 处理登录失败
  handleLoginFailure(err) {
    console.error('index_more handleLoginFailure:', err);
    this.setData({
      isLoggedIn: false,
      showHintPopup: true,
      hintMessage: '登录失败，请稍后重试',
    });
    wx.showToast({ title: '登录失败，请稍后重试', icon: 'none', duration: 2000 });
  },

  // 重试登录
  retryLogin() {
    const app = getApp();
    this.setData({ isLoading: true });
    app.doAutoLogin(true)
      .then((res) => {
        this.handleLoginSuccess(res);
        this.loadExpertPaths();
        this.setData({ isLoading: false });
      })
      .catch((err) => {
        this.handleLoginFailure(err);
        this.setData({ isLoading: false });
      });
  },

  // 加载专家学习路径
  loadExpertPaths() {
    const unionID = wx.getStorageSync('unionID');
    if (!unionID) {
      this.setData({
        isLoggedIn: false,
        isLoading: false,
        showHintPopup: true,
        hintMessage: '请先登录',
      });
      return;
    }

    // 将前端 kind 映射到数据库 kind 值
    const kindMap = {
      pujiao: '普教',
      gaojiao: '高教',
      zhijiao: '职教',
      congyezige: '从业资格',
      zhongshen: '终身学习',
    };
    const dbKind = kindMap[this.data.kind] || '';

    wx.showLoading({ title: '加载路径中...' });
    const jwtToken = wx.getStorageSync('jwt_token');
    wx.request({
      url: `${baseUrl}/expertPath/recommended`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${jwtToken}`,
      },
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 200 && res.data.success && res.data.paths) {
          let paths = res.data.paths;
          // 根据 kind 过滤路径
          if (dbKind) {
            paths = paths.filter((path) => path.kind === dbKind);
          }
          // 转换为页面所需格式
          const formattedPaths = paths.slice(0, this.data.limit).map((item) => ({
            pathID: item.pathID,
            goal: item.goal,
            subject: item.subject || 'general',
            pathLength: item.path ? item.path.length : 0,
            kind: item.kind || '普教', // 显示 kind 字段
          }));
          this.setData({
            expertPaths: formattedPaths,
            hasMore: paths.length > this.data.limit,
          });
        } else {
          this.setData({
            expertPaths: [],
            showHintPopup: true,
            hintMessage: '获取学习路径失败，请稍后重试',
          });
          wx.showToast({ title: '获取路径失败', icon: 'none' });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('loadExpertPaths 失败:', err);
        this.setData({
          expertPaths: [],
          showHintPopup: true,
          hintMessage: '网络错误，请检查网络后重试',
        });
        wx.showToast({ title: '网络错误', icon: 'none' });
      },
    });
  },

  // 加载更多路径（若支持分页）
  loadMorePaths() {
    const nextPage = this.data.page + 1;
    this.setData({ page: nextPage });
    this.loadExpertPaths();
  },

  // 跳转到专家路径对话页面
  goToExpertPath(e) {
    const pathID = e.currentTarget.dataset.pathId;
    if (!pathID) {
      wx.showToast({ title: '路径ID未定义', icon: 'none' });
      return;
    }

    const unionID = wx.getStorageSync('unionID');
    if (!unionID) {
      this.setData({
        showHintPopup: true,
        hintMessage: '请先登录',
      });
      return;
    }

    wx.navigateTo({
      url: `/pages/expertPath/expertConversation/expertConversation?pathID=${pathID}`,
      success: () => console.log(`跳转到专家路径对话成功，pathID: ${pathID}`),
      fail: (err) => {
        console.error('跳转失败:', err);
        this.setData({
          showHintPopup: true,
          hintMessage: '跳转失败，请稍后重试',
        });
      },
    });
  },

  // 隐藏提示弹窗
  hideHintPopup() {
    this.setData({ showHintPopup: false, hintMessage: '' });
  },

  // 阻止事件冒泡
  stopPropagation() {},

  // 获取分类标签
  getCategoryLabel(subject) {
    if (subject.includes('zk')) return '初中';
    if (subject.includes('gk')) return '高中';
    if (subject.includes('vocational')) return '职业教育';
    if (subject.includes('higher')) return '高等教育';
    if (subject.includes('professional')) return '从业资格';
    if (subject.includes('lifelong')) return '终身学习';
    return '通用';
  },

  // 获取分类样式
  getCategoryClass(subject) {
    if (subject.includes('zk') || subject.includes('gk')) return 'academic';
    if (subject.includes('vocational')) return 'vocational';
    if (subject.includes('higher')) return 'higher';
    if (subject.includes('professional')) return 'professional';
    if (subject.includes('lifelong')) return 'lifelong';
    return 'general';
  },

  // 用户点击右上角菜单中的“转发”
  onShareAppMessage() {
    const unionID = wx.getStorageSync('unionID') || '';
    const kind = this.data.kind || '';
    const sharePath = unionID
      ? `/pages/index_more/index_more?kind=${kind}&inviterID=${encodeURIComponent(unionID)}`
      : `/pages/index_more/index_more?kind=${kind}`;
    
    // 动态标题
    const kindMap = {
      pujiao: '基础教育学习路径',
      gaojiao: '高等教育学习路径',
      zhijiao: '职业教育学习路径',
      congyezige: '从业资格学习路径',
      zhongshen: '终身学习路径',
    };
    const shareTitle = kindMap[kind] ? `有约学习导航 - ${kindMap[kind]}` : '有约学习导航';

    if (!unionID) {
      wx.showToast({ title: '登录后分享可获得推荐奖励', icon: 'none' });
    }

    return {
      title: shareTitle,
      path: sharePath,
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    const unionID = wx.getStorageSync('unionID') || '';
    const kind = this.data.kind || '';
    const query = unionID
      ? `kind=${kind}&inviterID=${encodeURIComponent(unionID)}`
      : `kind=${kind}`;
    
    // 动态标题
    const kindMap = {
      pujiao: '基础教育学习路径',
      gaojiao: '高等教育学习路径',
      zhijiao: '职业教育学习路径',
      congyezige: '从业资格学习路径',
      zhongshen: '终身学习路径',
    };
    const shareTitle = kindMap[kind] ? `有约学习导航 - ${kindMap[kind]}` : '有约学习导航';

    return {
      title: shareTitle,
      query: query,
    };
  },
});